<!-- eslint-disable vue/no-useless-template-attributes -->
<!-- 工作日配置 -->
<template>
	<div class="container">
		<!-- 搜索条件 -->
		<yd-form :options="formOptions" :model="queryParams" :btns="formBtns"></yd-form>
		<!--查询列表-->
		<YdTable
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="getList"
			@currentChangeHandler="getList"
			@sortChangeHandler="getList"
		>
		</YdTable>
		<!-- 新增/删除 -->
		<el-dialog v-model="showAddOrDelete" :title="title" width="450px" append-to-body center>
			<el-form ref="workForm" :model="addOrDelForm" label-width="80px" :rules="rules">
				<el-form-item label="年份" prop="year">
					<el-date-picker v-model="addOrDelForm.year" type="year" :disabled-date="disabledDate" placeholder="请选择年份" />
					<el-tooltip v-if="title == '新增'" effect="light" :content="contentText" placement="top-start" style="z-index: 999; margin-left: 10px">
						<i class="question-icon">
							<svg-icon icon-class="question"></svg-icon>
						</i>
					</el-tooltip>
				</el-form-item>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button v-if="title == '新增'" type="primary" @click="handleAdd">确 定</el-button>
				<el-button v-if="title == '删除'" type="primary" @click="handleDelete">确 定</el-button>
				<el-button @click="handleClose(1)">取 消</el-button>
			</template>
		</el-dialog>
		<!-- 修改 -->
		<el-dialog v-model="showUpdate" title="修改日期类型" width="450px" append-to-body center>
			<el-form :model="updateForm" label-width="80px">
				<el-form-item label="日期">
					<el-input v-model="updateForm.day" placeholder="请输入日期" readonly />
				</el-form-item>
				<el-form-item label="类型">
					<el-radio-group v-model="updateForm.type">
						<el-radio v-for="dict in typeOptions" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="handleUpdate">确 定</el-button>
				<el-button @click="handleClose(0)">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script setup name="WorkDays" lang="tsx">
import { queryWeekdays, addWeekdays, updateWeekdays, delWeekdays } from '@/api/management/operationConfig/workdays';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { ref, reactive, onMounted, toRefs, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
const { proxy }: any = getCurrentInstance();

// 搜索表单数据
let queryParams = reactive<anyObj>({
	pageNum: 1,
	pageSize: 10,
	startTime: '',
	endTime: '',
});

const typeOptions = ref([
	{ label: '工作日', value: 1 },
	{ label: '节假日', value: 2 },
]);

// 日期范围
const disabledDate = (time: any) => {
	return time.getTime() > new Date('2200-12-31') || time.getTime() < new Date('1900-01-01');
};
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '日期类型',
		prop: 'type',
		children: [{ label: '全部', value: 0 }, ...typeOptions.value],
		selectKey: 'value',
		allOption: true,
	},
	{
		type: 'date-picker',
		label: '日期范围',
		prop: 'dateRange',
		span: 8,
		dateType: 'daterange',
		shortcutsKeys: ['lastWeek'],
		enableCrossDay: true,
		enableCrossWeek: true,
		attrs: {
			clearable: true,
		},
		defaulShortcutsKey: 'empty',
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: searchHandler,
	},
]);

// 列表相关
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '日期',
			prop: 'day',
			sortable: true,
		},
		{
			label: '星期',
			prop: 'dayWeekStr',
		},
		{
			label: '日期类型',
			prop: 'type',
			formatter: (row: anyObj, val: ApiVal) => {
				if (val === 1) {
					return '工作日';
				}
				return '节假日';
			},
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '修改',
					handler: (scope: anyObj) => openUpdate(scope.row),
					permi: ['weekdays:config:edit'],
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['weekdays:config:add'], handler: () => openAddOrDelete() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['weekdays:config:delete'], handler: () => openAddOrDelete(1) },
	],
	pagination: {
		isAsc: 'desc',
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	loading: false,
});
let tableData = ref([]);
// 弹框相关
const title = ref('');
const showAddOrDelete = ref(false);
const showUpdate = ref(false);
const contentText = ref('根据选定年份生成阳历日期数据，默认周一到周五为工作日，周六和周日为节假日，需根据指定年份的国家节假日自定义修改日期类型');
// 新增/删除参数
let addOrDelForm = reactive<anyObj>({
	year: '',
});
// 表单校验
const rules = ref({
	year: [{ required: true, message: '请选择相应年份', trigger: 'blur' }],
});
// 修改参数
let updateForm = reactive<anyObj>({
	day: '',
	type: null,
});
// 搜索按钮
function searchHandler() {
	queryParams.pageNum = 1;
	queryParams.pageSize = 10;
	console.log(queryParams);
	getList();
}
// 查询列表
function getList() {
	tableConfig.loading = true;
	tableData.value = [];
	queryWeekdays(queryParams).then((res: anyObj) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			proxy.$modal.msgError(res.msg);
			return;
		}
		tableConfig.pagination!.total = res.data.total;
		console.log(res);
		tableData.value = res.data.records;
	});
}

// 打开弹框
function openAddOrDelete(val?: ApiVal) {
	if (val === 1) {
		title.value = '删除';
	} else {
		title.value = '新增';
	}
	showAddOrDelete.value = true;
}
function openUpdate(row: anyObj) {
	updateForm.day = row.day;
	updateForm.type = row.type;
	showUpdate.value = true;
}

// 关闭弹框
function handleClose(val?: ApiVal) {
	if (val === 1) {
		addOrDelForm.year = '';
		console.log(typeOptions.value.slice(0));
		proxy.$refs.workForm.resetFields();
		showAddOrDelete.value = false;
	} else {
		showUpdate.value = false;
	}
}

// 添加整年
function handleAdd() {
	proxy.$refs['workForm'].validate((valid: anyObj) => {
		if (valid) {
			proxy.$modal
				.confirm('确认新增所选年份的所有日期数据?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
				.then(() => {
					const year = addOrDelForm.year.getFullYear();
					addWeekdays({
						startTime: year + '-01-01',
						endTime: year + 1 + '-01-01',
					}).then((res: ApiResponse) => {
						if (res.code !== 0) {
							proxy.$modal.msgWarning(res.msg);
							return;
						}
						searchHandler();
						handleClose(1);
						proxy.$modal.msgSuccess('新增成功！');
					});
				});
		}
	});
}
// 删除整年
function handleDelete() {
	proxy.$refs['workForm'].validate((valid: anyObj) => {
		if (valid) {
			proxy.$modal
				.confirm('确认删除所选年份的所有日期数据?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
				.then(() => {
					const year = addOrDelForm.year.getFullYear();
					// 调用接口
					delWeekdays({
						startTime: year + '-01-01',
						endTime: year + 1 + '-01-01',
					}).then((res: ApiResponse) => {
						if (res.code !== 0) {
							proxy.$modal.msgWarning(res.msg);
							return;
						}
						searchHandler();
						handleClose(1);
						proxy.$modal.msgSuccess('删除成功！');
					});
				});
		}
	});
}
// 修改单条
function handleUpdate() {
	updateWeekdays(updateForm).then((res: ApiResponse) => {
		showUpdate.value = false;
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			return;
		}
		proxy.$modal.msgSuccess('修改成功！');
		getList();
	});
}
searchHandler();
</script>
<style lang="scss" scoped>
.container {
	margin: 10px;
}
</style>
